/**
 * Created by hymn 2017/10/19.
 * cb-指callback回调
 */
;(function($, window, document,undefined) {
    //定义indexedDB的构造函数
    var DB = function(ele, opt) {
        this.$element = ele,
        this.defaults = {
			name   : "my_db",
			version: 1,
			db     : null,
			tableName:''
		},
        this.options = $.extend({}, this.defaults, opt)
	}
    //定义indexedDB的方法
    DB.prototype = {
        initDB:function(db,cb) {
            var options=this.options;
            options.version = options.version || 1;
            var request = window.indexedDB.open(options.name, options.version);
            request.onerror = function (e) {
                console.log(e.currentTarget.error.message);
            };
            request.onsuccess = function (e) {
                options.db = e.target.result;
                if(cb){
                 cb({
                        db:  db
                    })
                }
            };
            request.onupgradeneeded = function (e) {
                var thisDB = e.target.result;
                // options.db = thisDB;
                var tableName=options.tableName;
                if (!thisDB.objectStoreNames.contains(tableName)) {
                       var objStore = thisDB.createObjectStore(tableName, {keyPath: "img",autoIncrement:false});
                    objStore.createIndex("src", "src", {unique: false});

                }

            };
            this.options=options;
        },
        /**
        *新增表
        * configs 配置
        */
        addTable(configs){
            //configs={
            //        tableKey: 'id',  //key
            //        newTableName: '',  //新表名
            //        autoIncrement: false, //自增
            //        unique: false,  //唯一
            //        tableIndex:['value'],  //字段名
            //    }
            var options=this.options;
            var request = window.indexedDB.open(options.name, options.version);
            request.onerror = function (e) {
                console.log(e.currentTarget.error.message);
            };
            request.onsuccess = function (e) {
                options.db = e.target.result;
            };
            request.onupgradeneeded = function (e) {
                var thisDB = e.target.result;
                // options.db = thisDB;
                var tableName=configs.newTableName;
                var autoIncrement=configs.autoIncrement;
                var Index=configs.tableIndex;
                var unique=configs.unique;
                var key=configs.tableKey;
                if(tableName)
                    if (!thisDB.objectStoreNames.contains(tableName)) {
                        var objStore = thisDB.createObjectStore(tableName, {keyPath: key,autoIncrement:autoIncrement});
                        $.each(Index,function(i,v){
                            objStore.createIndex(v, v, {unique: unique});
                        });
                    }
            };
        },
        /**
        *关闭数据库
        * tableName 表名
        *  id  索引编号
		*/
        closeDB() {
            var options=this.options;
            options.db.close();
        },
        /**
        * 删除表
        * tableName 表名
        *  id  索引编号
        */
        deleteDB() {
            var dbObj=this.options;
            window.indexedDB.deleteDatabase(dbObj.name);
        },
         /**
        * 新增数据
        * tableName 表名
        *  id  索引编号
        */
        addData( tableName, data, cb) {
            var dbObj=this.options;
            var transaction = dbObj.db.transaction(tableName, 'readwrite');
            transaction.oncomplete = function () {
                console.log("transaction complete");
            };
            transaction.onerror = function (event) {
                console.dir(event)
            };

            var objectStore = transaction.objectStore(tableName);
            var request = objectStore.add(data);
            request.onsuccess = function (e) {
                if (cb) {
                    cb({
                        error: 0,
                        data : data
                    })
                }
            };
            request.onerror = function (e) {
                if (cb) {
                    cb({
                        error: 1
                    })
                }
            }
        },

        /**
        * 删除表对应数据
        * tableName 表名
        *  id  索引编号
        */
        deleteData(tableName, id, cb) {
            var dbObj=this.options;
            var transaction = dbObj.db.transaction(tableName, 'readwrite');
            transaction.oncomplete = function () {
                console.log("transaction complete");
            };
            transaction.onerror = function (event) {
                console.dir(event)
            };
            var objectStore = transaction.objectStore(tableName);
            var request = objectStore.delete(parseInt(id));
            request.onsuccess = function (e) {
                if (cb) {
                    cb({
                        error: 0,
                        data : parseInt(id)
                    })
                }
            };
            request.onerror = function (e) {
                if (cb) {
                    cb({
                        error: 1
                    })
                }
            }
        },
         /**
        * 获取表所有数据
        * tableName 表名
        *  id  索引编号
        */
        getDataAll(tableName, cb) {
            var dbObj=this.options;
            var transaction = dbObj.db.transaction(tableName, 'readonly');
            transaction.oncomplete = function () {
                console.log("transaction complete");
            };
            transaction.onerror = function (event) {
                console.dir(event)
            };

            var objectStore = transaction.objectStore(tableName);
            var rowData = [];
            objectStore.openCursor(IDBKeyRange.lowerBound(0)).onsuccess = function (event) {
                var cursor = event.target.result;
                if (!cursor && cb) {
                    cb({
                        error: 0,
                        data : rowData
                    });
                    return;
                }
                // rowData.push(cursor.value);
                if(cursor){
                    rowData.push(cursor.value)
                    cursor.continue();
                }

            };
            console.log(rowData)
            return rowData;
        },
         /**
        * 获取表id获取数据
        * tableName 表名
        *  id  索引编号
        */
        getDataById(tableName, id, cb) {
            var dbObj=this.options;
            var transaction = dbObj.db.transaction(tableName, 'readwrite');
            transaction.oncomplete = function () {
                console.log("transaction complete");
            };
            transaction.onerror = function (event) {
                console.dir(event)
            };

            var objectStore = transaction.objectStore(tableName);
            var request = objectStore.get(id);
            request.onsuccess = function (e) {
                if (cb) {
                    cb({
                        error: 0,
                        data : e.target.result
                    })
                }
            };
            request.onerror = function (e) {
                if (cb) {
                    cb({
                        error: 1
                    })
                }
            }
        };
    };
    //在插件中使用indexedDb对象
    $.fn.myPlugin = function(options,cb) {
        //创建indexedDb的实体
        var indexedDb= new DB(this, options);
        indexedDb.initDB(indexedDb,cb);
        //调用其方法
        return indexedDb;
    };
})(jQuery, window, document);

//初始化
var myDb={
           name: "pic_db",       
           version: 1,
           db: null,
           tableName:''
         }
$.fn.myPlugin (myDb,callback);